<?php
require_once('classes/config.inc.php');
include(DIR_CLASS. 'Session.php');
include(DIR_CLASS. 'TemplateParser.php');
include(DIR_CLASS. 'Mail.php');
include(DIR_CLASS. 'Form.php');

$session = new UserSession();
$session->open();
$captcha = new Captcha();
$captcha->open();

if(isset($_POST['action']) && $_POST['action'] == 'contact'){
	// REGISTER POST
	$form = new Form();
	$formElements = array("email" => 1,"message" => 1,"captcha" => 1,"subject"=>1);

	$form->open($formElements);

	$captcha = new Captcha();
	$captcha->open();
	
	if($form->isValidForm() && $captcha->check($form->get("captcha"))){
		
		if($session->check()){
			$email = $session->getEmail()."[REGISTERED] sended following message:\n". $form->get("message");
		}
		else{
			$email = $form->get("email")."[GUEST] sended following message:\n". $form->get("message");
		}
		
		$mailer = new Mail(SITE_NAME .": ".$form->get("subject"),$email);
		$mailer->send(SITE_EMAIL);
		if($mailer->isSended()){
			$error = "Email is successfully sended!";
		}
		else{
			$error = "Could not send the email. Try again please!";
		}
	}
	else{
		$error="Invalid input!";
	}
}

if($session->check()){
	$menu = "<a href=\"profile.php\">Profil</a> / <a href=\"login.php?act=logout\">Logga ut</a>[". substr($session->getEmail(),0,12) ."] / <a href=\"sitemap.php\">Karta &ouml;ver hemsidan</a>";
	$email = $session->getEmail();
}else{
	$menu = "<a href=\"register.php\">Registrera dig</a> / <a href=\"login.php\">Logga in</a> / <a href=\"sitemap.php\">Karta &ouml;ver hemsidan</a>";
	$email = "";
}

$captcha->save();
$template_array = array(
	"CAPTCHA" => $captcha->getQuestion(),
	"MENU" => $menu,
	"EMAIL" => $email,
	"ERROR" => isset($error)?$error:""
);
	
$template = new TemplateParser();
$template->loadfile("templates/contact.tpl");
$template->assignVars($template_array);
$template->output();
?>